package com.vq.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mongodb.client.result.DeleteResult;
import com.vq.entity.CollectNote;
import com.vq.entity.LikesNote;
import com.vq.entity.Trends;
import com.vq.mapper.CollectNoteMapper;
import com.vq.mapper.LikesNoteMapper;
import com.vq.mapper.TrendsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mapping.MappingException;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TrendsService {
    TrendsMapper trendsMapper;
    LikesNoteMapper likesNoteMapper;
    CollectNoteMapper collectNoteMapper;

    MongoTemplate mongoTemplate;

    @Autowired
    public TrendsService(TrendsMapper trendsMapper, LikesNoteMapper likesNoteMapper, CollectNoteMapper collectNoteMapper, MongoTemplate mongoTemplate) {
        this.trendsMapper = trendsMapper;
        this.likesNoteMapper = likesNoteMapper;
        this.collectNoteMapper = collectNoteMapper;
        this.mongoTemplate = mongoTemplate;
    }



    /**
     * 添加动态
     */
    public boolean insert(Trends trends) {
        if (trends==null) return false;
        String username = trends.getUsername();
        String account = trends.getAccount();
        if (account==null|| account.isEmpty()) return false;
        Trends.addCommunityTags(trends);//设置社区标签
        trends.setId(null);
        trendsMapper.insert(trends);
        return true;
    }



    /**
     * 删除动态
     */
    public void deleteByAccountAndId(String account, Long id) {
//        LambdaQueryWrapper<Trends> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Trends::getAccount, account).eq(Trends::getId, id);
//        trendsMapper.deleteById(lqw);
        trendsMapper.deleteByAccountAndId(account, id.intValue());
    }
    /**
     * 删除mongodb中的草稿
     * @param id 草稿id
     * @return
     */
    public boolean deleteByIdInMongo(Long id) {
        DeleteResult result = mongoTemplate.remove(new Query(Criteria.where("id").is(id)), Trends.class);
        System.out.println(result);
        return result.getDeletedCount()>0;//删除条数大于0条
    }



    /**
     * 查询所有动态
     */
    public List<Trends> selectAll() {
        List<Trends> trendsList = trendsMapper.selectList(null);
        //将社区标签从String转为list
        Trends.addComTags(trendsList);
        //反转集合
        Collections.reverse(trendsList);
        return trendsList;
    }
    public List<Trends> selectLimit(Integer limit) {
        List<Trends> trendsList;
        //查询最前20条数据
        if (limit==-1) {
            trendsList = trendsMapper.selectLimitToEnd(20);//查询后20条
        }
        else {
            Integer count = trendsMapper.count();
            //已经查询完毕
            if (limit>count) {
                return null;
            }
            //判断剩余动态是否足够20个
            else if (trendsMapper.count()-limit-21 < 0) {
                //只查询剩余动态
                trendsList = trendsMapper.selectLimit(0, trendsMapper.count() - limit - 1);//从当前往前20开始向后20查询
            }
            else {
                //查询20个
                trendsList = trendsMapper.selectLimit(trendsMapper.count() - limit - 21, 20);//从当前往前20开始向后20查询
            }
            //反转集合
            Collections.reverse(trendsList);
        }
        //将社区标签从String转为list
        Trends.addComTags(trendsList);
        return trendsList;
    }
    /**
     * 通过ID查询
     */
    public Trends selectById(Long id) {
        Trends trends = trendsMapper.selectById(id);
        Trends.addComTags(trends);
        return trends;
    }
    /**
     * 查询账号对应动态
     */
    public List<Trends> selectByAccount(String account) {
        LambdaQueryWrapper<Trends> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Trends::getAccount, account);
        List<Trends> trendsList = trendsMapper.selectList(lqw);
        Trends.addComTags(trendsList);
        //反转集合
        Collections.reverse(trendsList);
        return trendsList;
    }
    /**
     * 查询多个账号对应动态
     */
    public List<Trends> selectByAccount(List<String> list) {
        List<Trends> trendsList = new ArrayList<>();
        for (String s : list) {
            trendsList.addAll(this.selectByAccount(s));
        }
        trendsList.sort(new Comparator<Trends>() {
            @Override
            public int compare(Trends o1, Trends o2) {
                Long l = o2.getId() - o1.getId();
                return l.intValue();
            }
        });
        return trendsList;
    }
    /**
     * 搜素动态
     * @return
     */
    public List<Trends> searchTrends(String title) {
        LambdaQueryWrapper<Trends> lqw = new LambdaQueryWrapper<>();
        lqw.like(Trends::getTitle, title);
        List<Trends> trendsList = trendsMapper.selectList(lqw);
        Trends.addComTags(trendsList);
        //反转集合
        Collections.reverse(trendsList);
        return trendsList;
    }
    /**
     * 查询具有该标签的动态
     * @param name
     * @return
     */
    public List<Trends> selectByCommunityName(@RequestParam String name) {
        LambdaQueryWrapper<Trends> lqw = new LambdaQueryWrapper<>();
        lqw.like(Trends::getCommunityTags, name);
        List<Trends> trendsList = trendsMapper.selectList(lqw);
        Trends.addComTags(trendsList);
        //反转集合
        Collections.reverse(trendsList);
        return trendsList;
    }
    /**
     * 查询用户自己在mongo中的所有草稿
     * @param account 需要查询的用户
     * @return
     */
    public List<Trends> selectByMeInMongo(String account) {
        List<Trends> trendsList = mongoTemplate.find(new Query(Criteria.where("account").is(account)), Trends.class);
        //反转集合
        Collections.reverse(trendsList);
        return trendsList;
    }
    /**
     * 在mongodb中查询动态
     * @param id mongodb动态id
     * @return 返回通过_id查询的动态
     */
    public Trends selectByIdInMongo(Long id) {
        return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), Trends.class);
    }



    /**
     * 保存动态（草稿）
     * @param trends
     * @return
     */
    public Trends saveTrends(Trends trends) {
        boolean bo = true; //添加或者修改
        Trends trends1;//修改或添加后的动态
        if (trends.getId() != null) {
            trends1 = mongoTemplate.findById(trends.getId(), Trends.class);//查询该草稿是否以及存在
            if (trends1!=null) bo=false;
        }
        if (bo) { //添加草稿，生成随机ID
            trends.setId(Long.parseLong(new SimpleDateFormat("yyMMddHHmmssSSSS").format(System.currentTimeMillis())));
            trends1 = mongoTemplate.save(trends);
        } else { //修改草稿
            trends1 = mongoTemplate.save(trends);
        }
        return trends1;
    }
    /**
     * 通过账号account修改名称username
     * @param account 需要修改的账号
     * @param username 修改后的名称
     */
    public boolean updateToUsernameByAccount(String account, String username) {
        LambdaQueryWrapper<Trends> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Trends::getAccount, account);
        List<Trends> trendsList = trendsMapper.selectList(lqw);
        boolean bo = true;
        for (Trends trends : trendsList) {
            //只有当新名称与旧名称不等时才会进行修改操作
            if(!trends.getUsername().equals(username)) {
                trends.setUsername(username);
                int i = trendsMapper.updateById(trends);
                bo = bo ? i==1 : false;
            }
        }
        return bo;
    }
    /**
     * 点赞
     * @param account 点赞账号
     * @param trends_id 被点赞动态ID
     */
    public int like(String account, int trends_id) {
        Trends trends = trendsMapper.selectById(trends_id);
        //该动态不存在
        if (trends==null) return 0;
        //动态发布者不能为自己点赞
        if (trends.getAccount().equals(account)) return 0;
        //查询是否有点赞记录
        LambdaQueryWrapper<LikesNote> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LikesNote::getAccount, account).eq(LikesNote::getTrendsId, trends_id);
        LikesNote likesNote = likesNoteMapper.selectOne(lqw);
        //没有点过赞
        if (likesNote == null) {
            likesNoteMapper.insert(new LikesNote(account, trends_id));
            trends.setLikesNum(trends.getLikesNum()+1);
            trendsMapper.updateById(trends);
            return 1;
        }
        //点过赞（取消点赞）
        else {
            likesNoteMapper.delete(lqw);
            trends.setLikesNum(trends.getLikesNum()-1);
            trendsMapper.updateById(trends);
            return -1;
        }
    }
    /**
     * 收藏
     * @param account 收藏账号
     * @param trends_id 被收藏动态ID
     */
    public int collect(String account, int trends_id) {
        Trends trends = trendsMapper.selectById(trends_id);
        //该动态不存在
        if (trends==null) return 0;
        //动态发布者不能为自己点赞
        if (trends.getAccount().equals(account)) return 0;
        //查询是否有收藏记录
        LambdaQueryWrapper<CollectNote> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CollectNote::getAccount, account).eq(CollectNote::getTrendsId, trends_id);
        CollectNote collectNote = collectNoteMapper.selectOne(lqw);
        //没有收藏过
        if (collectNote == null) {
            collectNoteMapper.insert(new CollectNote(account, trends_id));
            trends.setCollectNum(trends.getCollectNum()+1);
            trendsMapper.updateById(trends);
            return 1;
        }
        //收藏过（取消收藏）
        else {
            collectNoteMapper.delete(lqw);
            trends.setCollectNum(trends.getCollectNum()-1);
            trendsMapper.updateById(trends);
            return -1;
        }
    }
    /**
     * 增加一次评论
     * @param trendsId
     * @return
     */
    public long critiqueTrends(long trendsId) {
        Trends trends = trendsMapper.selectById(trendsId);
        if (trends==null) return 0;
        trends.setCritiqueNum(trends.getCritiqueNum()+1);
        trendsMapper.updateById(trends);
        return trends.getCritiqueNum()+1;
    }
}
